package com.liry.security.config;

import com.alibaba.fastjson.JSONArray;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author ALI
 * @since 2023/6/15
 */
public class PermissionService extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {

    private Object filterObject;
    private Object returnObject;
    public PermissionService(Authentication authentication) {
        super(authentication);
    }

    public boolean hasPermission(String... permissions){
        if (permissions == null || permissions.length == 0) {
            return false;
        }
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        if (authorities.isEmpty()) {
            throw new AccessDeniedException("无权限！");
        }
        // 获取权限信息
        Set<String> resultPermissions = new HashSet<>();
        for (GrantedAuthority authority : authorities) {
            Object o = CacheManager.get(authority.getAuthority());
            if (o != null) {
                List<String> collect = JSONArray.parseArray(o.toString()).stream().map(Object::toString).collect(Collectors.toList());
                resultPermissions.addAll(collect);
            }
        }
        if (resultPermissions.isEmpty()) {
            throw new AccessDeniedException("无权限！");
        }
        return true;
    }
    @Override
    public void setFilterObject(Object filterObject) {
        this.filterObject =filterObject;
    }

    @Override
    public Object getFilterObject() {
        return filterObject;
    }

    @Override
    public void setReturnObject(Object returnObject) {
        this.returnObject = returnObject;
    }

    @Override
    public Object getReturnObject() {
        return this.returnObject;
    }

    @Override
    public Object getThis() {
        return this;
    }
}
